<template>
<div class="semCouponItem" :class="{'coupon-disabled': isEdit}">
  <h2 v-if="isEdit && model.totaled !== undefined">已发行{{model.totaled}}张</h2>
  <el-form class="forms" ref="form" :model="model" label-width="120px" :rules="rules" :disabled="isEdit">
    <el-form-item prop="name" label="优惠券名称:">
      <el-input v-model="model.name" :maxlength="30" show-word-limit></el-input>
    </el-form-item>
    <el-form-item prop="remarks" label="优惠券描述:">
      <el-input v-model="model.remarks" type='textarea' :autosize="{'minRows': 2}" :maxlength="200" show-word-limit></el-input>
    </el-form-item>
<!--    <el-form-item prop="icon" label="优惠券封面:">
      <y-upload-img
        :url="model.icon ? [{
          url: model.icon,
          id: model.attachmentId
        }] : []"
        valueType="ObjectArray"
        businessSysModuleCode="SEM_COUPON"
        :limit="1"
        re-upload
        :disabled="isEdit"
        :cropperOptions="{
          fixed: false
        }"
        @update="updateModel"></y-upload-img>
    </el-form-item>-->
    <el-form-item prop="businessType" label="优惠券所属:">
      <y-code-checkbox
        v-model="model.businessType"
        @change="() => changeBusiness(false)"
        :disabled-item="item => item.code === 'BUSINESS_MODULE_ADOPT'"
        dict="BUSINESS_MODULE"></y-code-checkbox>
    </el-form-item>
    <el-form-item prop="type" label="优惠方式:">
      <y-code-checkbox
        v-model="model.type"
        dict="SEM_COUPON_SALE_TYPE"
        @change="changeType"></y-code-checkbox>
    </el-form-item>
    <el-form-item prop="category" label="优惠券类别:">
      <y-code-checkbox
        v-model="model.category"
        :disabled="isExchange"
        @change="() => changeBusiness(false)"
        dict="SEM_COUPON_CATEGORY"></y-code-checkbox>
    </el-form-item>
    <!--  品类券  -->
    <template v-if="model.category === 'SEM_COUPON_CATEGORY_KIND'">
      <el-form-item
        label="商品类别:" prop="goodsCateVal" v-if="model.businessType === 'BUSINESS_MODULE_MALL'" class="is-required"
        :rules="spRules('请选择商品类别')">
        <el-cascader
          v-model="goodsCateVal"
          clearable
          :options="goodsCate"
          :props="{
            multiple: true,
            label: 'name',
            value: 'id'
          }"></el-cascader>
      </el-form-item>
      <el-form-item
        label="物品类别:" prop="adoptCateVal" v-if="model.businessType === 'BUSINESS_MODULE_ADOPT'" class="is-required"
        :rules="spRules('请选择物品类别')">
        <el-cascader
          v-model="adoptCateVal"
          clearable
          :options="adoptCate"
          :props="{
            multiple: true,
            label: 'cateName',
            value: 'cateCode'
          }"></el-cascader>
      </el-form-item>
    </template>
    <!--  物品券  -->
    <template v-if="model.category === 'SEM_COUPON_CATEGORY_INSTANCE'">
      <el-form-item
        label="物品SKU:" prop="adoptSKU" v-if="model.businessType === 'BUSINESS_MODULE_ADOPT'" class="is-required"
        :rules="spRules('请选择物品SKU')">
        <sem-adopt-coupon-select
          :disabled="isEdit"
          :selected="model.businessIds"
          :adopt-cate="adoptCate"
          :adopt-map="adoptMap"
          :adopt-sku-map="adoptSkuMap"
          @add="addBiz"
          @remove="delBiz"></sem-adopt-coupon-select>
      </el-form-item>
      <el-form-item
        label="商品SKU:" prop="goodsSKU" v-if="model.businessType === 'BUSINESS_MODULE_MALL'" class="is-required"
        :rules="spRules('请选择商品SKU')">
        <sem-goods-coupon-select
          :key="tableRefreshKey1"
          :multiple="!isExchange"
          :disabled="isEdit"
          :selected="model.businessIds"
          :goods-cate="goodsCate"
          :goods-map="goodsMap"
          :goods-sku-map="goodsSkuMap"
          @add="addBiz"
          @remove="delBiz"></sem-goods-coupon-select>
      </el-form-item>
    </template>
    <!--  商品券  -->
    <template v-if="model.category === 'SEM_COUPON_CATEGORY_PRODUCT'">
      <el-form-item
        label="商城商品:" prop="goodsProduct" v-if="model.businessType === 'BUSINESS_MODULE_MALL'" class="is-required"
        :rules="spRules('请选择商城商品')">
        <sem-goods-coupon-select
          :key="tableRefreshKey2"
          :disabled="isEdit"
          :selected="model.businessIds"
          :goods-cate="goodsCate"
          :goods-map="goodsMap"
          :goods-sku-map="goodsSkuMap"
          :select-sku="false"
          @change="changeBiz"></sem-goods-coupon-select>
      </el-form-item>
    </template>
    <template v-if="!isExchange">
      <el-form-item prop="usedScope" label="适用人群:" :rules='[{required: true, message: "请选择优惠券适用人群", trigger: "change"}]'>
        <y-code-checkbox
          v-model="model.usedScope"
          dict="SEM_COUPON_SCOPE"></y-code-checkbox>
      </el-form-item>
      <el-form-item
          prop="couponValue" label="优惠券面额(元):" v-if="model.type === 'SEM_COUPON_SALE_TYPE_DEDUCT'" :rules='[{required: true, message: "请输入优惠券面额", trigger: "blur"}]'>
        <el-input-number step-strictly :step="0.01" :controls="false" :min="1" v-model="model.couponValue"></el-input-number>
      </el-form-item>
      <el-form-item prop="discountRate" label="优惠券折扣(折):" v-if="model.type === 'SEM_COUPON_SALE_TYPE_DISCOUNT'" :rules='[{required: true, message: "请输入优惠券折扣(1~9.9)", trigger: "blur"}]'>
        <el-input-number :controls="false" step-strictly :step="0.1" :min="1" :max="9.9" v-model="model.discountRate"></el-input-number>
      </el-form-item>
      <el-form-item prop="rrestrict" label="消费限制:">
        <el-radio-group v-model="model.rrestrict">
          <el-radio label="0">无限制</el-radio>
          <el-radio label="1">有限制</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="restrictValue" label="最低消费(元):" v-if="model.rrestrict === '1'" :rules='[{required: true, message: "请输入最低消费金额", trigger: "blur"}]'>
        <el-input-number step-strictly :step="0.01" :min="1" :controls="false" v-model="model.restrictValue"></el-input-number>
      </el-form-item>
      <el-form-item prop="numRestrict" label="是否限领:">
        <el-radio-group v-model="model.numRestrict">
          <el-radio label="0">不限领</el-radio>
          <el-radio label="1">限领</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="num" label="限领数量(张):" v-if="model.numRestrict === '1'" :rules='[{required: true, message: "请输入限领数量", trigger: "blur"}]'>
        <el-input-number step-strictly :controls="false" :min="1" v-model="model.num"></el-input-number>
      </el-form-item>
    </template>
    <el-form-item prop="total" label="发行总量(张):">
      <el-input-number step-strictly :controls="false" :min="1" v-model="model.total"></el-input-number>
    </el-form-item>
  </el-form>
  <div class="buttons">
    <el-button size="mini" type="primary" @click="save">保存</el-button>
  </div>
</div>
</template>

<script>
import SemAdoptCouponSelect from "@/views/sem/semCouponItem/semAdoptCouponSelect";
import SemGoodsCouponSelect from "@/views/sem/semCouponItem/semGoodsCouponSelect";
export default {
  name: "semCouponItem",
  components: {SemGoodsCouponSelect, SemAdoptCouponSelect},
  props:{
    id: String
  },
  computed:{
    adoptCateVal:{
      get(){
        return (this.model.businessIds || []).map(v => v.split('/'));
      },
      set(val){
        this.model.businessIds = val.map(v => v.join('/'));
      }
    },
    goodsCateVal:{
      get(){
        return (this.model.businessIds || []).map(v => v.split('/'));
      },
      set(val){
        this.model.businessIds = val.map(v => v.join('/'));
      }
    },
    isExchange(){
      return this.model.type === 'SEM_COUPON_SALE_TYPE_EXCHANGE';
    }
  },
  created(){
    if(this.id){
      this.isEdit = true;
      this.$yAxios({
        url: this.$api.sem.queryCoupon,
        data:{
          id: this.id
        },
        loading: true
      }, info => {
        if(info.businessDetails){//初始化反显
          switch(info.businessType){
            case 'BUSINESS_MODULE_MALL':{
              if(info.businessDetails.infos && info.businessDetails.infos.length){
                info.businessDetails.infos.map(item => {
                  this.goodsMap[item.id] = item.name;
                })
              }
              if(info.businessDetails.skus && info.businessDetails.skus.length){
                info.businessDetails.skus.map(item => {
                  this.goodsSkuMap[item.id] = item.spData;
                })
              }
              break;
            }
            case 'BUSINESS_MODULE_ADOPT':{
              if(info.businessDetails.infos && info.businessDetails.infos.length){
                info.businessDetails.infos.map(item => {
                  this.adoptMap[item.id] = item.name;
                })
              }
              if(info.businessDetails.skus && info.businessDetails.skus.length){
                info.businessDetails.skus.map(item => {
                  this.adoptSkuMap[item.id] = Object.values(JSON.parse(item.specJson)).join(';');
                })
              }
              break;
            }
          }
        }
        //初始化businessIds
        if(Array.isArray(info.businessRelations)){
          info.businessIds = info.businessRelations.map(item => item.businessId);
        }else{
          info.businessIds = [];
        }
        this.$delete(info, 'businessDetails');
        this.$delete(info, 'businessRelations');
        this.changeBusiness(true, info);
        Object.keys(info).map(key => {
          this.$set(this.model, key, info[key] === null ? '' : info[key]);
        })
      })
    }
  },
  data(){
    return {
      goodsCate: [],
      adoptCate: [],
      goodsMap: {},// 物品id,name键值对
      goodsSkuMap: {},//id,name键值对
      adoptMap: {},// 物品id,name键值对
      adoptSkuMap: {},//sku id,name键值对
      tableRefreshKey1: 1,
      tableRefreshKey2: 2,
      isEdit: false,
      model: {
        name: '',
        type: '',
        remarks: '',
        usedScope: '',
        businessType: '',
        category: '',
        businessIds: [],
        // mutex: '0',
        couponValue: undefined,
        discountRate: undefined,
        attachmentId: '',
        icon: '',
        numRestrict: '1',
        num: '',
        rrestrict: '1',
        restrictValue: undefined,
        status: '0',
        total: undefined,
        totaled: ''
      },
      rules:{
        name: [{required: true, message: "请输入优惠券名称", trigger: "blur"}],
        /*icon: [{required: true, message: "请上传优惠券封面", trigger: "change"}],*/
        businessType: [{required: true, message: "请选择优惠券所属", trigger: "change"}],
        category: [{required: true, message: "请选择优惠券类别", trigger: "change"}],
        type: [{required: true, message: "请选择优惠券抵扣方式", trigger: "change"}],
        total: [{required: true, message: "请输入发行总量", trigger: "blur"}],
      }
    }
  },
  methods:{
    spRules(str){
      return [{
        validator: (rule, value, callback) => {
          if(!this.model.businessIds.length){
            callback(new Error(str));
          }
          else{
            callback();
          }
        },
        trigger: "change"
      }]
    },
    generateForms(){
      let form = {...this.model};
      if(form.type === 'SEM_COUPON_SALE_TYPE_DEDUCT'){
        this.$delete(form, 'discountRate');
      }
      if(form.type === 'SEM_COUPON_SALE_TYPE_DISCOUNT'){
        this.$delete(form, 'couponValue');
      }
      if(form.type === 'SEM_COUPON_SALE_TYPE_EXCHANGE'){
        this.$delete(form, 'couponValue');
        this.$delete(form, 'discountRate');
      }
      if(form.rrestrict !== '1'){
        this.$delete(form, 'restrictValue');
      }
      if(form.numRestrict !== '1'){
        this.$delete(form, 'num');
      }
      return form;
    },
    save(){
      this.$refs['form'].validate(valid => {
        if(valid){
          this.$yAxios({
            url: this.$api.sem.saveCoupon,
            data: this.generateForms(),
            loading: true
          }, info => {
            this.$message({
              type: 'success',
              message: '保存成功'
            });
            this.$emit('close-drawer');
            this.$emit('refresh');
          })
        }
      })
    },
    updateModel({type, file}){
      switch(type) {
        case 'delete': {
          this.model.attachmentId = '';
          this.model.icon = '';
          break;
        }
        case 'edit': case 'add':{
          this.model.attachmentId = file.id;
          this.model.icon = file.name;
          this.$refs['form'].validateField('icon');
          break;
        }
      }
    },
    changeType(){
      //优惠方式变化的回调
      this.model.businessIds = [];
      this.tableRefreshKey1 += 2;
      this.tableRefreshKey2 += 2;
      if(this.isExchange){
        this.model.category = 'SEM_COUPON_CATEGORY_INSTANCE'
      }
    },
    changeBusiness(isInit, model=this.model){
      if(!isInit){
        model.businessIds = [];
        this.tableRefreshKey1 += 2;
        this.tableRefreshKey2 += 2;
      }
      switch(model.businessType){
        case 'BUSINESS_MODULE_MALL':{//商城卷
          switch(model.category){
            case 'SEM_COUPON_CATEGORY_KIND':{//品类券
              //加载商品品类树
              this.getGoodsCate();
              break;
            }
            case 'SEM_COUPON_CATEGORY_PRODUCT':{//商品券
              //加载商品物品列表
              this.getGoodsCate();
              break;
            }
            case 'SEM_COUPON_CATEGORY_INSTANCE':{//物品券
              //加载商品物品列表
              this.getGoodsCate();
              break;
            }
          }
          break;
        }
        case 'BUSINESS_MODULE_ADOPT':{//物卷
          switch(model.category){
            case 'SEM_COUPON_CATEGORY_KIND':{//品类券
              //加载物品类树
              this.getAdoptCate();
              break;
            }
            case 'SEM_COUPON_CATEGORY_INSTANCE':{//物品券
              //加载物品列表
              this.getAdoptCate();
              break;
            }
          }
          break;
        }
      }
    },
    addBiz({value, rootName, skuName}){
      if(this.isExchange){
        this.model.businessIds.splice(0, 1, value)
      }else{
        this.model.businessIds.push(value);
      }
      //处理name用于反显
      this.model.businessIds.sort();
    },
    delBiz({value}){
      let delIndex = this.model.businessIds.indexOf(value);
      if(delIndex >= 0){
        this.$delete(this.model.businessIds, delIndex);
      }
    },
    changeBiz(value){
      this.$set(this.model, 'businessIds', value);
    },
    getAdoptCate(){
      if(!this.adoptCate.length){
        this.$yAxios({
          url: this.$api.adopt.queryAdoptCategory,
        }, info => {
          this.adoptCate = info.filter(item => !!item.children);
        })
      }
    },
    getGoodsCate(){
      if(!this.goodsCate.length){
        this.$yAxios({
          url: this.$api.goods.getAllClassify,
        }, info => {
          this.goodsCate = info.filter(item => item.tag === 0);
        })
      }
    }
  }
}
</script>

<style scoped lang="less">
.semCouponItem{
  height: 100%;
  padding: 20px 20px 0;
  >h2{
    text-align: center;
    height: 40px;
    line-height: 40px;
    margin: 0;
  }
  >.forms{
    height: calc(100% - 40px);
    overflow-y: auto;
  }
  >.buttons{
    text-align: center;
    height: 40px;
    >.el-button{
      min-width: 104px;
    }
  }
  &.coupon-disabled{
    >.forms{
      //height: 100%;
    }
    >.buttons{
      display: none;
    }
  }
}
</style>